package producersConsumersTests.InserterThroughput;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import producersConsumersTests.utils.DataGetter;


/**
 * SleepyCollector is a Runnable which acts the follows: It sleeps for one
 * second, and then loops over all running tasks (specified by T) and gets data
 * from them. It saves the data in a hash map, sorted by the time of collection
 * and sleeps again.
 * 
 * @param <T>
 *            the type of tasks the collector loops over
 */
public class SleepyCollector<T extends Runnable> implements Runnable {
	private static final long SLEEP_TIME_MILLIES = 1000;
	private boolean stop = false;
	private HashMap<Integer, List<Long>> results = new HashMap<Integer, List<Long>>();
	private T boys[];
	private DataGetter<T> getter;
	private int time = 0;

	public SleepyCollector(DataGetter<T> getter, T boys[]) {
		this.boys = boys;
		this.getter = getter;
	}

	@Override
	public void run() {
		try {
			while (!stop) {
				Thread.sleep(SLEEP_TIME_MILLIES);
				time++;
				LinkedList<Long> l = new LinkedList<Long>();
				this.results.put(time, l);
				for (T i : boys) {
					l.add(getter.getDataFrom(i));
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void stop() {
		this.stop = true;
	}

	public Map<Integer, List<Long>> getResults() {
		return results;
	}
}
